package com.liuyun.unixsocket;

import jnr.unixsocket.UnixSocket;
import jnr.unixsocket.UnixSocketAddress;
import jnr.unixsocket.UnixSocketChannel;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.logging.Logger;

/**
 * <p>
 * Copyright: (C), 2021/2/18 17:46
 * <p>
 * <p>
 * Company Information & Data Security Solutions Co., Ltd.
 *
 * @author LiuYun liujw@idss-cn.com
 * @version 1.0
 */
public class UnixDockerClient {
    private static final Logger LOGGER = Logger.getLogger(UnixDockerClient.class.getName());
    public static void main(String[] args) throws IOException {
        // 建立 Unix Socket 连接
        File sockFile = new File("/var/run/docker.sock");
        UnixSocketAddress address = new UnixSocketAddress(sockFile);
        UnixSocketChannel channel = UnixSocketChannel.open(address);
        try (UnixSocket unixSocket = new UnixSocket(channel)) {

            // 调用 Docker API
            PrintWriter w = new PrintWriter(unixSocket.getOutputStream());
            w.println("GET /v1.39/images/json HTTP/1.1");
            w.println("Host: http");
            w.println("Accept: */*");
            w.println("");
            w.flush();
            // 关闭 Output，否则会导致下面的 read 操作一直阻塞
            unixSocket.shutdownOutput();

            // 获取返回结果
            LOGGER.info("---- Docker Response ----");
            BufferedReader br = new BufferedReader(new InputStreamReader(unixSocket.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}
